package com.jandar.util;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zhengt
 * @date 2022/10/21
 */
public class RtsUtilv2 {

    /**
     * 改造rts
     *
     * @param pdfFile pdf文件
     * @return {@link List}<{@link Map}<{@link String}, {@link String}>>
     */
    public static List<Map<String, String>> remoldRts(File pdfFile) {
        return null;
    }

    /**
     * 改造rts
     *
     * @param document 文档
     * @return {@link List}<{@link Map}<{@link String}, {@link String}>>
     */
    public static List<Map<String, String>> remoldRts(String document) {
        if (isBlank(document)) {
            return new ArrayList<>();
        }
        document = document
                .replaceAll("x=[\\d.]+, y=[\\d.]+, text=", "")
                .replaceAll("[ \\t ]+", "")
                .replaceAll("\\r\\n", "\n")
                .replaceAll("\r\n", "\n")
                .replaceAll("\n+", " ");

        // List<String> records = regAll("(\\d+ \\d{4}-.*?(?=\\d+ \\d{4}-|说明)|\\d+ \\d{4}-.*)", document, 1);
        List<String> records = regAll("((\\d+ \\d{4}-|\\d{4}-\\d{2}).*?(?=\\d{4}-\\d{2}| \\d+ \\d{4}-|说明)|\\d+ \\d{4}-.*)", document, 1);
        return records.stream()
                .map(s -> {
                    String xh;
                    String kssj = "";
                    String thsc = "";
                    if (isMatch("^\\d{4}-\\d{1,2}-\\d{1,2}", s)) {
                        String[] splits = s.split(" ");
                        int n = splits.length;
                        xh = reg("(\\d+) \\d{2}:\\d{2}:\\d{2}", s, 1);
                        kssj = reg("(\\d{4}-\\d{1,2}-\\d{1,2})", s, 1) + " " + reg("(\\d{2}:\\d{2}:\\d{2})", s, 1);
                        for (int i = 1; i < 5 && i < n; i++) {
                            if (splits[i].matches("[\\d分秒]{1,3}")) {
                                thsc += splits[i];
                            }
                        }
                        for (int i = 11; i < 14 && i < n ;i ++) {
                            if (splits[i].matches("[\\d分秒]{1,3}")) {
                                thsc += splits[i];
                            }
                        }
                    } else {
                        String[] splits = s.split(" ");
                        int n = splits.length;
                        xh = splits[0];
                        kssj = splits[1] + " " + splits[2];
                        if (!kssj.matches("(\\d{4}-\\d{1,2}-\\d{1,2}) (\\d{2}:\\d{2}:\\d{2})")) {
                            kssj = reg("(\\d{4}-\\d{1,2}-\\d{1,2})", s, 1) + " " + reg("(\\d{2}:\\d{2}:\\d{2})", s, 1);
                        }
                        for (int i = 2; i < 7 && i < n; i++) {
                            if (splits[i].matches("[\\d分秒]{1,3}")) {
                                thsc += splits[i];
                            }
                        }
                        for (int i = 17; i < 20 && i < n; i++) {
                            if (splits[i].matches("[\\d分秒]{1,3}")) {
                                thsc += splits[i];
                            }
                        }
                    }
                    String txlx = reg(" (国内被叫?|本地主叫?|国内异地?) ", s, 1) +
                            reg(" (叫?本地|叫?异地|地主叫|叫) ", s, 1);
                    String txfs = reg(" (被叫|主叫) ", s, 1);
                    String dfhm = reg(" (被叫|主叫) (\\d+)", s, 2);
                    String dfhmlx = reg("(中国[电联移][信通动]?|[电联移][信通动]转售?)", s, 1);
                    if (dfhmlx.matches("[电联移][信通动]转售?")) {
                        dfhmlx += "售";
                    } else if (dfhmlx.contains("电")) {
                        dfhmlx += "信";
                    } else if (dfhmlx.contains("联")) {
                        dfhmlx += "通";
                    } else if (dfhmlx.contains("移")) {
                        dfhmlx += "动";
                    }
                    if (s.contains("固定")) {
                        dfhmlx += "固定";
                    }

                    String thd = reg("(中国[电联移] ?[信通动]?固?定?|[电联移][信通动]转 ?售?) (.*?)", s, 2);
                    String ywmc = isMatch("4G ?高清", s) ? "4G高清语音" : isMatch("超清 ?语音|超清", s) ? "超清语音" : "";
                    String gnthf = reg("(\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+)", s, 1);
                    String gjctf = reg("(\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+)", s, 2);
                    String xxf = reg("(\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+)", s, 3);
                    String fyxj = reg("(\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+)", s, 4);

                    String yhx_prefix = reg("((超清|4G ?高清) ([^\\d]+?) [^\\s.()（）]+ )", s, 3);
                    String yhx = reg(
                            "(\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+) (\\d+\\.\\d+) (.+?) ([^\\d\\s（）()]+?) ([\\da-zA-Z]+) ([\\da-zA-Z]+)", s, 5);
                    yhx = (yhx_prefix + yhx).replaceAll("[\t ]", "");
                    String dfthszd = reg("([^\\d\\s（）()]+?) ([\\da-zA-Z]+) ([\\da-zA-Z]+)", s, 1);
                    String lac = reg("([^\\d\\s（）()]+?) ([\\da-zA-Z]+) ([\\da-zA-Z]+)", s, 2);
                    String cellid = reg("([^\\d\\s（）()]+?) ([\\da-zA-Z]+) ([\\da-zA-Z]+)", s, 3);
                    Map<String, String> ans = new LinkedHashMap<>();
                    ans.put("序号", xh);
                    ans.put("起始时间", kssj);
                    ans.put("通话时长", thsc);
                    ans.put("通信类型", txlx);
                    ans.put("通信方式", txfs);
                    ans.put("对方号码", dfhm);
                    ans.put("对方号码类型", dfhmlx);
                    ans.put("通话地", thd);
                    ans.put("业务名称", ywmc);
                    ans.put("国内通话费/国际及台港澳漫游费", gnthf);
                    ans.put("国际及台港澳长途费", gjctf);
                    ans.put("信息费", xxf);
                    ans.put("费用小计", fyxj);
                    ans.put("优惠项", yhx);
                    ans.put("对方通话所在地", dfthszd);
                    ans.put("通话所在LAC", lac);
                    ans.put("通话所在CELLID", cellid);
                    return ans;
                })
                .filter(j -> isNotBlank(j.get("序号")))
                .collect(Collectors.toList());
    }

    /**
     * 判断正则是否匹配
     *
     * @param regx regx
     * @param text 文本
     * @return boolean
     */
    private static boolean isMatch(String regx, String text){
        if(isBlank(text)){
            return false;
        }
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(text);
        return matcher.find();
    }

    /**
     * 匹配指定位置的文本
     *
     * @param regx regx
     * @param txt  三种
     * @param num  全国矿工工会
     * @return {@link String}
     */
    private static String reg(String regx, String txt, int num) {
        if (isBlank(regx) || isBlank(txt)) {
            return "";
        }
        Matcher m = findMatcher(regx,txt);
        String result = "";
        if(m.find()){
            result = m.group(num);
        }
        result = result != null ? result.trim() : "";
        return result;
    }

    /**
     * 获取匹配的列表
     *
     * @param regx regx
     * @param txt  三种
     * @param num  全国矿工工会
     * @return {@link List}<{@link String}>
     */
    private static List<String> regAll(String regx, String txt, int num) {
        if (isBlank(txt)) {
            return new ArrayList<>();
        }
        Matcher m = findMatcher(regx, txt);
        List<String> strList = new ArrayList<>();
        while(m.find()){
            String str = m.group(num);
            if (isNotBlank(str)) {
                strList.add(str);
            }
        }
        return strList;
    }

    /**
     * 获取正则匹配
     *
     * @param regx regx
     * @param txt  三种
     * @return {@link Matcher}
     */
    private static Matcher findMatcher(String regx, String txt) {
        return Pattern.compile(regx).matcher(txt);
    }
    
    /**
     * 是空白
     *
     * @param str str
     * @return boolean
     */
    private static boolean isBlank(CharSequence str) {
        int length;
        if ((str == null) || ((length = str.length()) == 0)) {
            return true;
        }
        for (int i = 0; i < length; i++) {
            if (!isBlankChar(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    /**
     * 不是空白
     *
     * @param str str
     * @return boolean
     */
    private static boolean isNotBlank(CharSequence str) {
        return !isBlank(str);
    }
    /**
     * 是空白字符
     *
     * @param c c
     * @return boolean
     */
    private static boolean isBlankChar(int c) {
        return Character.isWhitespace(c)
                || Character.isSpaceChar(c)
                || c == '\ufeff'
                || c == '\u202a'
                || c == '\u0000';
    }
}
